package com.retlife.tvshow.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.widget.LinearLayout
import com.retlife.tvshow.R
import com.retlife.tvshow.global.manager.BgmManager
import com.retlife.tvshow.serial_port.bike.model.BikeData
import kotlin.math.max
import kotlin.math.roundToInt

class GameView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs) {

    private var isPause: Boolean = true
    private var countDown: Int = 0
    private var prepare: Boolean = false

    //    private val playerViewList = mutableListOf<PlayerView>()
    private var a = false
    private var playerCount: Int = 8
    private var lastMax = 0
    private val totalProcess = mutableListOf<Int>()
    private val modeList = mutableListOf<Boolean>()

    //角色在场景可移动的最大的位置
    private val maxLength: Int = 8000
    private val maxWith = 10000f
    private val maxProcess: Int = Int.MAX_VALUE
    private var max: Int = 0
    private var marginP = 0
    private var playerViewHeight = 0
    private var runningRange = 0

    private
    var padding = 0

    private var first = -1
    private var second = -1
    private var third = -1

    private val bgDrawable: Bitmap
    private val icon_frist: Bitmap
    private val icon_second: Bitmap
    private val icon_third: Bitmap
    private val icon_1: Bitmap
    private val icon_2: Bitmap
    private val icon_3: Bitmap
    private val icon_4: Bitmap
    private val icon_5: Bitmap
    private val icon_6: Bitmap
    private val icon_7: Bitmap
    private val icon_8: Bitmap

    private var z = 0
    private val p1: Bitmap
    private val p2: Bitmap
    private val p3: Bitmap
    private val p4: Bitmap
    private val r1: Bitmap
    private val r2: Bitmap
    private val r3: Bitmap
    private val wm1: Bitmap
    private val wm2: Bitmap

    private lateinit var icon_frist_copy: Bitmap
    private lateinit var icon_second_copy: Bitmap
    private lateinit var icon_third_copy: Bitmap
    private lateinit var icon_1_copy: Bitmap
    private lateinit var icon_2_copy: Bitmap
    private lateinit var icon_3_copy: Bitmap
    private lateinit var icon_4_copy: Bitmap
    private lateinit var icon_5_copy: Bitmap
    private lateinit var icon_6_copy: Bitmap
    private lateinit var icon_7_copy: Bitmap
    private lateinit var icon_8_copy: Bitmap
    private lateinit var bgDrawableCopy: Bitmap
    private lateinit var p1Copy: Bitmap
    private lateinit var p2Copy: Bitmap
    private lateinit var p3Copy: Bitmap
    private lateinit var p4Copy: Bitmap
    private lateinit var r1Copy: Bitmap
    private lateinit var r2Copy: Bitmap
    private lateinit var r3Copy: Bitmap
    private lateinit var wm1Copy: Bitmap
    private lateinit var wm2Copy: Bitmap
    private val paint = Paint()
    private val matrix = Matrix()
    private var oldew = 0
    private var oldeh = 0

    init {
        orientation = VERTICAL
        dividerDrawable = ColorDrawable(Color.WHITE)
        setBackgroundColor(Color.parseColor("#000000"))
        gravity = Gravity.BOTTOM
        bgDrawable = BitmapFactory.decodeResource(resources, R.mipmap.bg_game)
        icon_frist = BitmapFactory.decodeResource(resources, R.mipmap.icon_frist)
        icon_second = BitmapFactory.decodeResource(resources, R.mipmap.icon_sceond)
        icon_third = BitmapFactory.decodeResource(resources, R.mipmap.icon_third)
        icon_1 = BitmapFactory.decodeResource(resources, R.mipmap.icon_1)
        icon_2 = BitmapFactory.decodeResource(resources, R.mipmap.icon_2)
        icon_3 = BitmapFactory.decodeResource(resources, R.mipmap.icon_3)
        icon_4 = BitmapFactory.decodeResource(resources, R.mipmap.icon_4)
        icon_5 = BitmapFactory.decodeResource(resources, R.mipmap.icon_5)
        icon_6 = BitmapFactory.decodeResource(resources, R.mipmap.icon_6)
        icon_7 = BitmapFactory.decodeResource(resources, R.mipmap.icon_7)
        icon_8 = BitmapFactory.decodeResource(resources, R.mipmap.icon_8)

        p1 = BitmapFactory.decodeResource(resources, R.mipmap.p1)
        p2 = BitmapFactory.decodeResource(resources, R.mipmap.p2)
        p3 = BitmapFactory.decodeResource(resources, R.mipmap.p3)
        p4 = BitmapFactory.decodeResource(resources, R.mipmap.p4)
        r3 = BitmapFactory.decodeResource(resources, R.mipmap.r3)
        r2 = BitmapFactory.decodeResource(resources, R.mipmap.r2)
        r1 = BitmapFactory.decodeResource(resources, R.mipmap.r1)
        wm1 = BitmapFactory.decodeResource(resources, R.mipmap.wm1)
        wm2 = BitmapFactory.decodeResource(resources, R.mipmap.wm2)
    }


    fun changeProcess(intArray: MutableList<BikeData>) {
        if (prepare || isPause)
            return
        z++
        for (i in 0 until intArray.size) {
            if (i >= totalProcess.size) {
                totalProcess.add(i, intArray[i].speed)
                modeList.add(i, intArray[i].isActive)
            } else {

                totalProcess[i] = totalProcess[i] + intArray[i].speed
                modeList[i] = intArray[i].isActive
            }
//            playerViewList[i].setProcess(totalProcess[i])
            /* playerViewList[i].setSpeed(intArray[i].speed)
             playerViewList[i].setActive(intArray[i].isActive)*/

        }
        lastMax = max
        for (i in 0 until totalProcess.size) {
            max = max(max, totalProcess[i])
        }
        if (max > maxLength) {
            padding = max - maxLength
        }
//        for (i in 0 until totalProcess.size) {
//            playerViewList[i].setProcess(totalProcess[i] - padding, totalProcess[i])
//        }
        var rankingMax: Int
        for (i in 0 until totalProcess.size) {
            if (max == totalProcess[i]) {
                first = i
                break
            }
        }
        rankingMax = 0
        for (i in 0 until totalProcess.size) {
            if (i == first)
                continue
            rankingMax = max(rankingMax, totalProcess[i])
            if (rankingMax == totalProcess[i]) {
                second = i
            }
        }
        rankingMax = 0
        for (i in 0 until totalProcess.size) {
            if (i == first || i == second)
                continue
            rankingMax = max(rankingMax, totalProcess[i])
            if (rankingMax == totalProcess[i]) {
                third = i
            }
        }
        if (max >= maxProcess) {
            isPause = true
        }
        invalidate()
    }

    fun setPlayerCount(playerCount: Int) {
        this.playerCount = playerCount
        totalProcess.clear()
        modeList.clear()
        z = 0
        padding = 0
        for (i in 0 until playerCount) {
            totalProcess.add(i, 0)
            modeList.add(i, false)
        }
        /* for (i in 0 until playerCount) {
             val playerView = PlayerView(context = context, null)
             playerView.setPlayer(i)
             playerViewList.add(playerView)
             addView(playerView)
         }*/
        invalidate()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Log.i(javaClass.simpleName, "onSizeChanged:w:$w ,h:$h,oldw$oldw,oldh$oldeh")

    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        Log.i(javaClass.simpleName, "onLayout: changed$changed,l$l,t$t,r$r,b$b")

    }

    @SuppressLint("DrawAllocation")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (measuredHeight <= 0 || measuredWidth <= 0)
            return
        if (measuredHeight == oldeh && measuredWidth == oldew)
            return
        Log.i(javaClass.simpleName, "onMeasure: oldeh$oldeh,oldew$oldew,measuredWidth$measuredWidth,measuredHeight$measuredHeight")

        oldeh = measuredHeight
        oldew = measuredWidth
        runningRange = (measuredHeight * (9.2 / 10.0f)).roundToInt()
        playerViewHeight = (measuredHeight * (2.8 / 10.0f)).roundToInt()
        val margin = runningRange - (playerViewHeight * playerCount)
        marginP = 0
        if (playerCount > 1) {
            marginP = margin / (playerCount - 1)
        }
        /* for (playerView in playerViewList) {
             val layoutParams: LinearLayout.LayoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
             layoutParams.height = playerViewHeight
             layoutParams.topMargin = marginP
             playerView.layoutParams = layoutParams
         }*/
        val scale: Float = (measuredWidth * 0.156f) / (icon_frist.width * 1.0f)
        matrix.setScale(scale, scale)
        icon_frist_copy = Bitmap.createBitmap(icon_frist, 0, 0, icon_frist.width, icon_frist.height, matrix, false)
        icon_second_copy = Bitmap.createBitmap(icon_second, 0, 0, icon_second.width, icon_second.height, matrix, false)
        icon_third_copy = Bitmap.createBitmap(icon_third, 0, 0, icon_third.width, icon_third.height, matrix, false)
        val scale1 = (icon_frist_copy.height * 0.54f) / (icon_1.height)
        matrix.setScale(scale1, scale1)
        icon_1_copy = Bitmap.createBitmap(icon_1, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_2_copy = Bitmap.createBitmap(icon_2, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_3_copy = Bitmap.createBitmap(icon_3, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_4_copy = Bitmap.createBitmap(icon_4, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_5_copy = Bitmap.createBitmap(icon_5, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_6_copy = Bitmap.createBitmap(icon_6, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_7_copy = Bitmap.createBitmap(icon_7, 0, 0, icon_1.width, icon_1.height, matrix, false)
        icon_8_copy = Bitmap.createBitmap(icon_8, 0, 0, icon_1.width, icon_1.height, matrix, false)

        val scale2: Float = (measuredWidth * 1.0f) / (bgDrawable.width * 1.0f)
        matrix.setScale(scale2, scale2)
        bgDrawableCopy = Bitmap.createBitmap(bgDrawable, 0, 0, bgDrawable.width, bgDrawable.height, matrix, false)

        val scale5: Float = (playerViewHeight * 1.0f) / (p1.height * 1.0f)
        matrix.setScale(scale5, scale5)
        p1Copy = Bitmap.createBitmap(p1, 0, 0, p1.width, p1.height, matrix, true)
        p2Copy = Bitmap.createBitmap(p2, 0, 0, p2.width, p2.height, matrix, true)
        p3Copy = Bitmap.createBitmap(p3, 0, 0, p3.width, p3.height, matrix, true)
        p4Copy = Bitmap.createBitmap(p4, 0, 0, p4.width, p4.height, matrix, true)
        val scale3: Float = (p1Copy.height * 0.35f) / (wm1.height * 1.0f)
        matrix.setScale(scale3, scale3)
        wm1Copy = Bitmap.createBitmap(wm1, 0, 0, wm1.width, wm1.height, matrix, true)
        wm2Copy = Bitmap.createBitmap(wm2, 0, 0, wm2.width, wm2.height, matrix, true)
        val scale4: Float = (p1Copy.height * 0.112f) / (r1.height * 1.0f)
        matrix.setScale(scale4, scale4)
        r1Copy = Bitmap.createBitmap(r1, 0, 0, r1.width, r1.height, matrix, true)
        r2Copy = Bitmap.createBitmap(r2, 0, 0, r2.width, r2.height, matrix, true)
        r3Copy = Bitmap.createBitmap(r3, 0, 0, r3.width, r3.height, matrix, true)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
//        Log.i(javaClass.simpleName, "onDraw: ")

        /*val widthPercent = width / 8f
        val left = (max(max, maxLength) - maxLength) % maxWith * width / maxWith % (widthPercent * 2f)
        val left1 = (max(max, maxLength) - maxLength) % 1000f
        for (i in 0 until 10) {
            canvas.drawText("${(max(max, maxLength) - maxLength) / 1000 + i}0m", ((1000 * i - left1) / 10000 * width), height / 24f * 3, paint)

            if (i % 2 == 1) {
                continue
            }

            canvas.drawLine((widthPercent * i - left), (height / 6).toFloat(), (widthPercent * (i + 1) - left), (height / 6).toFloat(), paint)
            canvas.drawLine((widthPercent * i - left), (height / 6 * 5).toFloat(), (widthPercent * (i + 1) - left), (height / 6 * 5).toFloat(), paint)
        }*/
        val leftPadding = (max(max, maxLength) - maxLength) % maxWith
        val scale: Float = (width * 1.0f) / (bgDrawable.width * 1.0f)
        matrix.setScale(scale, scale)
        val toInt = ((maxWith - leftPadding) / maxWith * bgDrawable.width).toInt()
        val roundToInt = ((leftPadding) / maxWith * bgDrawable.width).toInt()
        if (toInt <= 0 || leftPadding <= 0 || roundToInt <= 0) {
//            val bitmapRes = Bitmap.createBitmap(bgDrawable, 0, 0, bgDrawable.width, bgDrawable.height, matrix, false)
            canvas.drawBitmap(bgDrawableCopy, 0f, 0f, paint)
        } else {
//            val bitmapRes = Bitmap.createBitmap(bgDrawable, (bgDrawable.width - toInt), 0, toInt, bgDrawable.height, matrix, false)
//            val bitmapRes1 = Bitmap.createBitmap(bgDrawable, 0, 0, roundToInt, bgDrawable.height, matrix, false)
            canvas.drawBitmap(bgDrawableCopy, 0f - (bgDrawable.width - toInt), 0f, paint)
            canvas.drawBitmap(bgDrawableCopy, (maxWith - leftPadding) / maxWith * width - 1, 0f, paint)

        }
        if (prepare) {
            paint.textSize = (height / 6).toFloat()
            paint.color = resources.getColor(R.color.red)
            if (countDown > 0) {
                canvas.drawText(countDown.toString(), (width / 2).toFloat(), (height / 2).toFloat(), paint)
            } else {
                canvas.drawText("GO", (width / 2).toFloat(), (height / 2).toFloat(), paint)

            }
        } else {
            canvas.drawBitmap(icon_frist_copy, 0.167f * width - icon_frist_copy.width * 0.5f, 0.25f * icon_frist_copy.height, null)
            canvas.drawBitmap(icon_second_copy, 0.5f * width - icon_second_copy.width * 0.5f, 0.25f * icon_second_copy.height, null)
            canvas.drawBitmap(icon_third_copy, 0.833f * width - icon_third_copy.width * 0.5f, 0.25f * icon_third_copy.height, null)
            canvas.drawBitmap(getIndexRes(first), 0.167f * width + icon_frist_copy.width * 0.21f, 0.48f * icon_frist_copy.height, null)
            canvas.drawBitmap(getIndexRes(second), 0.5f * width + icon_second_copy.width * 0.21f, 0.48f * icon_second_copy.height, null)
            canvas.drawBitmap(getIndexRes(third), 0.833f * width + icon_third_copy.width * 0.21f, 0.48f * icon_third_copy.height, null)
            /*paint.textSize = (height / 16).toFloat()
            val s = "第二名：玩家${second + 1}"
            val measureText = paint.measureText(s)
            canvas.drawText("第一名：玩家${first + 1}", 0f, (height / 12).toFloat(), paint)
            canvas.drawText("第二名：玩家${second + 1}", (width / 2 - measureText / 2), (height / 12).toFloat(), paint)
            canvas.drawText("第三名：玩家${third + 1}", (width - measureText), (height / 12).toFloat(), paint)*/
        }
        if (padding < p1Copy.width) {
            val fl = height * 0.25f
            paint.setColor(
                Color
                    .parseColor("#ffffff")
            )
            paint.strokeWidth = 10f
            canvas.drawLine((p1Copy.width - padding).toFloat(), fl, (p1Copy.width - padding).toFloat(), height.toFloat(), paint)
        }
        for (i in 0 until playerCount) {
            if (i >= totalProcess.size)
                break
            val bitmapCopy = if (z % 30 < 8) {
                p1Copy
            } else if (z % 30 < 15) {
                p2Copy
            } else if (z % 30 < 23) {
                p3Copy
            } else {
                p4Copy
            }
            val value = width * ((totalProcess[i] - padding) / 10000f)
            val fl = height - runningRange + (playerViewHeight + marginP) * i.toFloat()
            canvas.drawBitmap(bitmapCopy, value, fl, paint)
            val bitmapCopy1 = if (modeList[i]) {
                if (z % 30 < 15)
                    wm1Copy
                else
                    wm2Copy

            } else {
                if (z % 30 < 10)
                    r1Copy
                else if (z % 30 < 20)
                    r2Copy
                else
                    r3Copy

            }
            if (modeList[i])
                canvas.drawBitmap(bitmapCopy1, value - bitmapCopy1.width * 0.77f, fl + (playerViewHeight - bitmapCopy1.height).toFloat(), null)
            else
                canvas.drawBitmap(bitmapCopy1, value - bitmapCopy1.width * 0.70f, fl + (playerViewHeight - bitmapCopy1.height * 1.6f), null)
            val iconIndexCopy = getIndexRes(i)

            canvas.drawBitmap(iconIndexCopy, value + (bitmapCopy.width) * 0.50f, fl + 0.02f * bitmapCopy.height, null)
        /*    paint.textSize = iconIndexCopy.height*0.5f
            canvas.drawText("${i + 1}", value + bitmapCopy.width, fl+iconIndexCopy.height*0.5f, paint)*/
        }
    }

    fun getIndexRes(index: Int): Bitmap {
        return when (index % 8) {
            0 -> icon_1_copy
            1 -> icon_2_copy
            2 -> icon_3_copy
            3 -> icon_4_copy
            4 -> icon_5_copy
            5 -> icon_6_copy
            6 -> icon_7_copy
            7 -> icon_8_copy
            else -> icon_8_copy
        }
    }

    fun start() {
        this.prepare = true
        this.isPause = false
        this.countDown = 3
        Thread {
            while (prepare) {
                if (countDown >= 0) {
                    postInvalidate()
                    Thread.sleep(1000)
                    countDown--
                } else {
                    prepare = false
                    BgmManager.instance?.playBgm()

                }

            }
        }.start()
        BgmManager.instance?.countDown()
    }

    fun reStart() {
        reset()
        start()
    }

    private fun reset() {
//        totalProcess.clear()
//        modeList.clear()
        setPlayerCount(playerCount)
        BgmManager.instance?.stopBgm()
        lastMax = 0
        max = 0
        /*  for (i in 0 until playerCount) {
              playerViewList[i].setSpeed(0)
              playerViewList[i].setProcess(0, 0)
          }*/
    }

    fun stop() {
        reset()
    }

    fun pause() {
        this.isPause = true
        BgmManager.instance?.pause()

    }

    fun resume() {
        this.isPause = false
        BgmManager.instance?.resume()
    }


}